package com.renwenhao.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
    private static final int WIDTH = 120;
    private static final int HEIGHT = 32;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        BufferedImage bufferedImage = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_BGR);
        Graphics graphics = bufferedImage.getGraphics();

        //设置bg
        graphics.setColor(Color.red);
        graphics.fillRect(0,0,WIDTH,HEIGHT);

        //设置边框
        graphics.setColor(Color.BLACK);
        graphics.drawRect(0,0,WIDTH-1, HEIGHT-1);

        // 随机数字
        Random r = new Random();

        // 字母数字组合
        StringBuilder charForNumAndWord = getCharForNumAndWord();
        graphics.setFont(new Font(null, Font.BOLD, 24));
        graphics.setColor(Color.BLUE);
        // checkcode session
        StringBuilder sessionCheckCode = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            int i1 = r.nextInt(charForNumAndWord.toString().length());
            sessionCheckCode.append(charForNumAndWord.charAt(i1));
            graphics.drawString(String.valueOf(charForNumAndWord.charAt(i1)),WIDTH/4 * i, HEIGHT/5 * 3);
        }
        HttpSession session = request.getSession();
        session.setAttribute("checkCode", sessionCheckCode.toString());
        graphics.setColor(Color.BLACK);
        // 划线
        for (int i = 0; i < 4; i++) {
            int x1 = r.nextInt(WIDTH);
            int x2 = r.nextInt(WIDTH);
            int y1 = r.nextInt(HEIGHT);
            int y2 = r.nextInt(HEIGHT);

            graphics.drawLine(x1, y1,x2,y2);
        }




        response.setContentType("image/jpeg");
        ImageIO.write(bufferedImage,"jpg",response.getOutputStream());
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }

    public StringBuilder getCharForNumAndWord(){
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 127; i++) {
            sb.append((char) (i+1));
        }
        String s = sb.toString().replaceAll("[^a-zA-Z0-9]", "");

        StringBuilder stringBuilder = new StringBuilder(s);
        return stringBuilder;
    }
}
